package Java面试周阳.阻塞队列.生消模型;

import jdk.nashorn.internal.runtime.ECMAException;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 资源类
 */
public class ShareData {
    private int number = 0;

    private Lock lock = new ReentrantLock();

    private Condition condition = lock.newCondition();

    public void increment() throws Exception {
        // 同步代码块
        lock.lock();
        try {
            // 判断
            while (number != 0) {
                // 等待不能生产
                condition.await();
            }
            // 干活
            number++;

            System.out.println(Thread.currentThread().getName() + "\t" + number);

            // 通知唤醒
            condition.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void decrement() throws Exception {
        // 同步代码块
        lock.lock();
        try {
            // 判断
            while (number == 0) {
                // 等待不能消费
                condition.await();
            }
            // 干活
            number--;

            System.out.println(Thread.currentThread().getName() + "\t" + number);

            // 通知唤醒
            condition.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
